local Worship = Class(function(self, inst)
    self.inst = inst

    -- 展示物存档字段
    self.prefab = nil
    self.skinname = nil
    self.skin_id = nil
    self.userid = nil
    self.show = false

    -- 冷却标记
    self.cooling = false
end)

local TAGS = {
    "monster", "hostile", "scarytoprey", "canbetrapped", "smallcreature", "spider", "trader",
    "animal", "prey", "rabbit", "cattoy", "catfood", "cookable"
}

---------------------------------------------------------
-- 铜钱雨（根据鱼重量持续 1~5 秒）
---------------------------------------------------------
function Worship:StartCoinRain(fish)
    if fish == nil or fish.components.weighable == nil then
        return
    end

    local weight = fish.components.weighable:GetWeightPercent() or 0
    local duration = 1 + weight * 4 -- 1~5 秒

    local inst = self.inst
    local elapsed = 0

    -- 每 0.3 秒执行一次
    local task
    task = inst:DoPeriodicTask(0.3, function()
        -- 超时 -> 停止
        if elapsed >= duration then
            task:Cancel() -- ← 终止执行
            return
        end
        elapsed = elapsed + 0.3

        ------------------------------------------------
        -- 生成铜钱（你已有的逻辑）
        ------------------------------------------------
        local x, y, z = inst.Transform:GetWorldPosition()
        local dx = math.random(-2, 2)
        local dz = math.random(-2, 2)
        local pos = Vector3(x + dx, y + 20, z + dz)

        local item = SpawnPrefab("bboy_copper_coin")
        if item ~= nil then
            if item.Physics ~= nil then
                item.Physics:Teleport(pos:Get())
            else
                item.Transform:SetPosition(pos:Get())
            end

            if item.components.inventoryitem then
                item.components.inventoryitem:DoDropPhysics(pos.x, pos.y, pos.z, true, 0.5)
            end
        end
    end)
end

---------------------------------------------------------
-- 移除当前供品（内部函数）
---------------------------------------------------------
function Worship:ClearOffer()
    if self.inst.show_item ~= nil then
        self.inst.show_item:Remove()
        self.inst.show_item = nil
    end

    -- 清空展示记录
    self.prefab = nil
    self.skinname = nil
    self.skin_id = nil
    self.userid = nil
    self.show = false
end

---------------------------------------------------------
-- 设置展示（带冷却）
---------------------------------------------------------
function Worship:SetShow(inst, old_item, show, doer)
    -- 不显示：清除供品，结束
    if not show then
        self:ClearOffer()
        return
    end

    if old_item == nil then
        return
    end

    ---------------------------------------------------------
    -- 保存数据用于存档
    ---------------------------------------------------------
    self.prefab   = old_item.prefab
    self.skinname = old_item.skinname
    self.skin_id  = old_item.skin_id
    self.userid   = old_item.userid
    self.show     = true

    ---------------------------------------------------------
    -- 生成展示实体
    ---------------------------------------------------------
    if (old_item.components and old_item.components.stackable) or not doer then
        local item
        if self.skinname ~= nil then
            item = SpawnPrefab(self.prefab, self.skinname, self.skin_id, self.userid)
        else
            item = SpawnPrefab(self.prefab)
        end
        if item == nil then
            return
        end

        if item.Follower == nil then
            item.entity:AddFollower()
        end
        item.entity:SetParent(inst.entity)
        item.Follower:FollowSymbol(inst.GUID, "food", nil, nil, nil, true)

        for _, v in ipairs(TAGS) do
            item:RemoveTag(v)
        end
        item:AddTag("INLIMBO")
        item:AddTag("NOCLICK")
        item.inlimbo = true
        item:StopBrain()

        if item.Physics then item.Physics:SetActive(false) end
        if item.DynamicShadow then item.DynamicShadow:Enable(false) end
        if item.MiniMapEntity then item.MiniMapEntity:SetEnabled(false) end
        if item.components.health then item.components.health:SetInvincible(true) end
        if item.components.perishable then item.components.perishable:StopPerishing() end
        if item.components.edible then item:RemoveComponent("edible") end

        inst.show_item = item
    else
        old_item.components.inventoryitem:RemoveFromOwner(true)
        if old_item.Follower == nil then
            old_item.entity:AddFollower()
        end
        old_item.entity:SetParent(inst.entity)
        old_item.Follower:FollowSymbol(inst.GUID, "food", nil, nil, nil, true)

        for _, v in ipairs(TAGS) do
            old_item:RemoveTag(v)
        end
        old_item:AddTag("INLIMBO")
        old_item:AddTag("NOCLICK")
        old_item.inlimbo = true
        old_item:StopBrain()

        if old_item.Physics then old_item.Physics:SetActive(false) end
        if old_item.DynamicShadow then old_item.DynamicShadow:Enable(false) end
        if old_item.MiniMapEntity then old_item.MiniMapEntity:SetEnabled(false) end
        if old_item.components.health then old_item.components.health:SetInvincible(true) end
        if old_item.components.perishable then old_item.components.perishable:StopPerishing() end
        if old_item.components.edible then old_item:RemoveComponent("edible") end

        inst.show_item = old_item
    end


    if doer then
        if old_item.components.weighable ~= nil and old_item:HasTag("fish") then
            self:StartCoinRain(old_item)
        end
        if old_item:HasTag("preparedfood") and old_item.components.edible and old_item.components.edible.foodtype == "MEAT" then
            doer:AddDebuff("bboy_buff_bring_wealth", "bboy_buff_bring_wealth")
        end
    end

    ---------------------------------------------------------
    -- 开启 5 分钟冷却计时器（300 秒）
    ---------------------------------------------------------
    self.cooling = true
    self.inst.components.timer:StartTimer("worship_cooldown", 300)

    return true
end

---------------------------------------------------------
-- 定时器结束：清理供品 + 取消冷却
---------------------------------------------------------
function Worship:OnTimerDone(name)
    if name == "worship_cooldown" then
        -- 清除展示物
        self:ClearOffer()
        self.cooling = false
    end
end

---------------------------------------------------------
-- 存档
---------------------------------------------------------
function Worship:OnSave()
    if not self.show or self.prefab == nil then
        return {}
    end

    return {
        show     = true,
        prefab   = self.prefab,
        skinname = self.skinname,
        skin_id  = self.skin_id,
        userid   = self.userid,
        cooling  = self.cooling,
    }
end

---------------------------------------------------------
-- 读档
---------------------------------------------------------
function Worship:OnLoad(data)
    if data == nil then
        return
    end

    self.cooling = data.cooling or false

    -- 若之前有展示，则恢复供品
    if data.show and data.prefab then
        self:SetShow(self.inst, {
            prefab   = data.prefab,
            skinname = data.skinname,
            skin_id  = data.skin_id,
            userid   = data.userid,
        }, true)
    end

    -- 若冷却中，还需继续 timer
    if self.cooling then
        -- 若读档已经过了一部分时间，timer 组件会自己处理剩余时间
        if not self.inst.components.timer:TimerExists("worship_cooldown") then
            self.inst.components.timer:StartTimer("worship_cooldown", 300)
        end
    end
end

return Worship
